package top.abrsm.util;

import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;

import static com.github.wxpay.sdk.WXPayUtil.HMACSHA256;
import static com.github.wxpay.sdk.WXPayUtil.MD5;

public class PayUtil {

    /**
     * 微信支付生成签名
     * 这个方法是从微信sdk里copy过来的，自己也可以写，要注意生成签名后UTF-8的转换，要不然容易报签名Body UTF-8错误
     *
     * @param data 待签名数据
     * @param key  API密钥
     */
    public static String createSign ( final Map<String, String> data, String key ) {
        //根据规则创建可排序的map集合
        Set<String> keySet = data.keySet ();
        String[] keyArray = keySet.toArray ( new String[keySet.size ()] );
        Arrays.sort ( keyArray );
        StringBuilder sb = new StringBuilder ();
        for ( String k : keyArray ) {
            if ( k.equals ( WXPayConstants.FIELD_SIGN ) ) {
                continue;
            }
            if ( data.get ( k ).trim ().length () > 0 ) { // 参数值为空，则不参与签名
                sb.append ( k ).append ( "=" ).append ( data.get ( k ).trim () ).append ( "&" );
            }
        }
        sb.append ( "key=" ).append ( key );
        //转换UTF-8
        //String str = new String(sb.toString().getBytes("UTF-8"));
        try {
            if ( WXPayConstants.SignType.MD5.equals ( WXPayConstants.SignType.MD5 ) ) {
                return MD5 ( sb.toString () ).toUpperCase ();
            } else if ( WXPayConstants.SignType.HMACSHA256.equals ( WXPayConstants.SignType.MD5 ) ) {
                return HMACSHA256 ( sb.toString (), key );
            } else {
                throw new Exception ( String.format ( "Invalid sign_type: %s", WXPayConstants.SignType.MD5 ) );
            }
        } catch ( Exception e ) {
            e.printStackTrace ();
            return null;
        }
    }


    /**
     * 微信支付调统一下单API
     *
     * @param orderInfo
     * @return
     */
    public static String httpOrder ( String orderInfo ) {
        String url = ConstUtil.BASH_PATH;
        try {
            HttpURLConnection conn = ( HttpURLConnection ) new URL ( url ).openConnection ();
            //加入数据
            conn.setRequestMethod ( "POST" );
            conn.setDoOutput ( true );
            BufferedOutputStream buffOutStr = new BufferedOutputStream ( conn.getOutputStream () );
            buffOutStr.write ( orderInfo.getBytes ( "UTF-8" ) );
            buffOutStr.flush ();
            buffOutStr.close ();
            //获取输入流
            BufferedReader reader = new BufferedReader ( new InputStreamReader ( conn.getInputStream (), "UTF-8" ) );
            String line = null;
            StringBuffer sb = new StringBuffer ();
            while ( ( line = reader.readLine () ) != null ) {
                sb.append ( line );
            }
            Map<String, String> map = WXPayUtil.xmlToMap ( sb.toString () );
            //返回字段很多，这里只取我们所需的字段
            String return_code = map.get ( "return_code" );//状态码
            String result_code = map.get ( "result_code" );//业务结果
            String code_url = map.get ( "code_url" );
            //根据微信文档return_code 和result_code都为SUCCESS的时候才会返回code_url
            if ( null != map && "SUCCESS".equals ( return_code ) && "SUCCESS".equals ( result_code ) ) {
                return code_url;
            } else {
                return null;
            }
        } catch ( Exception e ) {
            e.printStackTrace ();
        }
        return null;
    }

}
